package com.fary.chapter02_safe_thread;

/**
 * 线程不安全的示例：
 * 当多个线程共享同一个全局变量时，将可能会发生线程安全的代码
 * 上锁，保证只有拿到锁的线程才可以执行，没有拿到锁的线程不可以执行，需要阻塞等待。
 */
public class NotSafeThread implements Runnable {

    private static Integer count = 100;

    @Override
    public void run() {
        while (count > 1) {
            cal();
        }
    }

    private  void cal() {
        try {
            Thread.sleep(20);
        } catch (Exception e) {
            e.printStackTrace();
        }
        count--;
        System.out.println(Thread.currentThread().getName() + "," + count);
    }


    public static void main(String[] args) {
        NotSafeThread notSafeThread = new NotSafeThread();
        Thread thread1 = new Thread(notSafeThread);
        Thread thread2 = new Thread(notSafeThread);
        thread1.start();
        thread2.start();
    }
}
